package com.lp.common.component;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPattern;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-03-30 10:08:19
 */
@Component
public class UrlFetcher implements ApplicationContextAware {


    private ApplicationContext applicationContext;

    /**
     * 解析项目内所有的URL，留作后期RBAC用
     */
//    @PostConstruct
    public void fetchUrls() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        System.out.println("解析URL");
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();

        handlerMethods.forEach((key, value) -> {
            for (RequestMethod method : key.getMethodsCondition().getMethods()) {
                String m = method.name();
                PathPatternsRequestCondition pathPatternsCondition = key.getPathPatternsCondition();
                if (pathPatternsCondition != null) {
                    for (PathPattern pattern : pathPatternsCondition.getPatterns()) {
                        System.out.println(m + pattern.getPatternString());
                    }
                }
            }
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
